﻿using System;
using System.Collections.Generic;
using System.Device.Location;

namespace SimpleRadar
{
    public enum DistanceType { Miles, Kilometers };
    public static class GeoCoordinateEx
    {
        public static double DistanceTo(this GeoCoordinate obj,GeoCoordinate endPoint,DistanceType type)
        {
            double R = (type == DistanceType.Miles) ? 3960 : 6371;
            double dLat = toRadian(endPoint.Latitude - obj.Latitude);
            double dLon = toRadian(endPoint.Longitude - obj.Longitude);
            double a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) +
            Math.Cos(toRadian(obj.Latitude)) * Math.Cos(toRadian(endPoint.Latitude)) *
            Math.Sin(dLon / 2) * Math.Sin(dLon / 2);
            double c = 2 * Math.Asin(Math.Min(1, Math.Sqrt(a)));
            double d = R * c;
            return d;
        }
        private static double toRadian(double val)
        {
            return (Math.PI / 180) * val;
        }
        public static GeoCoordinate GetAtDistanceBearing(this GeoCoordinate point,
                                                     double distance, double bearing)
        {
            const double degreesToRadian = Math.PI / 180.0;
            const double radianToDegrees = 180.0 / Math.PI;
            const double earthRadius = 6378137.0;

            var latA = point.Latitude * degreesToRadian;
            var lonA = point.Longitude * degreesToRadian;
            var angularDistance = distance / earthRadius;
            var trueCourse = bearing * degreesToRadian;

            var lat = Math.Asin(
                Math.Sin(latA) * Math.Cos(angularDistance) +
                Math.Cos(latA) * Math.Sin(angularDistance) * Math.Cos(trueCourse));

            var dlon = Math.Atan2(
                Math.Sin(trueCourse) * Math.Sin(angularDistance) * Math.Cos(latA),
                Math.Cos(angularDistance) - Math.Sin(latA) * Math.Sin(lat));

            var lon = ((lonA + dlon + Math.PI) % (Math.PI * 2)) - Math.PI;

            var result = new GeoCoordinate(lat * radianToDegrees, lon * radianToDegrees);

            return result;
        }
        public static IList<GeoCoordinate> GetCirclePoints(this GeoCoordinate center,
                                   double radius, int nrOfPoints = 50)
        {
            var angle = 360.0 / nrOfPoints;
            var locations = new List<GeoCoordinate>();
            for (var i = 0; i <= nrOfPoints; i++)
            {
                //circle.Path.Add(p);
                locations.Add(GeoCoordinateEx.GetAtDistanceBearing(center,radius, angle * i));
            }
            return locations;
        }
    }
}
